import { $waterloo } from '@/api/http';
import { AuthModel, JwtPayload } from '@/models/waterloo';
import { VueRouter } from 'vue-router/types/router';

export function login(auth: AuthModel) {
    return $waterloo
        .post('/login', {}, {auth})
        .then(({data}) => data);
}

export function check() {
    return $waterloo
        .get<JwtPayload>('/check')
        .then(({data}) => data);
}

export function routerGuard(router: VueRouter) {
    router.beforeEach(async (to, from, next) => {
        if (to.name !== 'login') {
            try {
                await check();
                next();
            } catch (e) {
                next({name: 'login'});
            }
        } else {
            next();
        }
    });
}